package com.zhb.cloud.core.component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.zhb.cloud.mail.model.Email;
import com.zhb.cloud.mail.service.EmailService;

/**
 * @ClassName: MailQueueConsumer
 * @author: zhb
 * @date: 2017年11月25日 下午12:25:06
 * @Description: 邮件消费者
 *
 */
public class MailQueueConsumer {
	private static final Logger logger = LoggerFactory.getLogger(MailQueueConsumer.class);
	@Autowired
	private EmailService mailService;

	@PostConstruct
	public void startThread() {
		ExecutorService e = Executors.newFixedThreadPool(2);// 两个大小的固定线程池
		e.submit(new PollMail(mailService));
		e.submit(new PollMail(mailService));
	}

	class PollMail implements Runnable {
		EmailService mailService;

		public PollMail(EmailService mailService) {
			this.mailService = mailService;
		}

		@Override
		public void run() {
			while (true) {
				try {
					Email mail = MailQueueProduce.getMailQueue().consume();
					if (mail != null) {
						logger.info("剩余邮件总数:{}", MailQueueProduce.getMailQueue().size());
						mailService.sendSimpleEmail(mail);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	@PreDestroy
	public void stopThread() {
		logger.info("destroy");
	}
}
